package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

/**
 * Servlet implementation class Auth
 */
//@WebServlet(urlPatterns = { "/Auth" })
public class Auth extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Auth() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String userId = request.getParameter("userID");
		String password = request.getParameter("password");
		String jsonResult = "";
		String message = "";
		int status = 2;
		/* 
		 * 1 比對身份成功且有權限
		 * 2 比對身份失敗
		 * 3 無任何權限
		 * */

		QueryTask queryTask = new QueryTask();
		ArrayList<String> rlts = new ArrayList<String>();
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT nickName FROM tms_personnel WHERE userID=? AND pwd=?";
		int size = 0;
		String nickName = "";
		
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, userId);
			ps.setString(2, password);
			rs = ps.executeQuery();
			
			boolean isMatch = rs.next()?true:false;
			if (isMatch) { //表示輸入的User存在
				nickName = rs.getString("nickName");
				status = 3;	//比對成功先將狀態改為3 (無任何權限)
				strSQL = "SELECT COUNT(*) FROM tms_authorization_body WHERE userId=?";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, userId);
				rs = ps.executeQuery();
				rs.next();
				 // create a session if one does not exist
			    // 需要使用 true 當作 getSession() 的參數
			    HttpSession session = request.getSession(true);
			    session.setAttribute("userId", userId);
				size= rs.getInt(1);
				
				if ( size>0 ) {	//該User 是有被分配Group的，接著來看該User有那些工作待處理
					status = 1;	//有權限將狀態改為1 (比對身份成功且有權限)
					
					/** 取得此ID所擁有的角色清單 2012/08/16 **/
					strSQL = "select t2.roleName from tms_roleusermapping t1, tms_role t2 where t1.roleID = t2.roleID AND userID=?";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, userId);
					rs = ps.executeQuery();
					while (rs.next()) {
						rlts.add(rs.getString("roleName"));
					}
					queryTask.setRoleLists(rlts);
					
					strSQL = "INSERT INTO activiti.tms_log_loginout (userID, type, createdDate) VALUES (?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, userId);
					ps.setInt(2, 1);
					ps.setTimestamp(3, wid.currentTimeStamp());
					ps.execute();
				} else {
					message = "User ID："+userId +" 並無擁有任何權限";
				}
			} else {
				message = "User ID 或 Password 不存在！";
			}
		} catch (SQLException e) {
			message = "{\"errorMsg\":\""+wid.keepErrorMes(conn, ps, e, "", true)+"\"}";
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				message = e.toString();
			}
		}
		queryTask.setNickName(nickName);
		queryTask.setStatus(status);
		queryTask.setSize(size);
		queryTask.setMessage(message);
		jsonResult = new Gson().toJson(queryTask);
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonResult);
	}
}

class QueryTask {
	String message;
	int size;
	int status;
	String nickName;
	ArrayList<String> roleLists;

	public String getNickName() {
		return nickName;
	}

	public ArrayList<String> getRoleLists() {
		return roleLists;
	}

	public void setRoleLists(ArrayList<String> roleLists) {
		this.roleLists = roleLists;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public int getStatus() {
		return this.status;
	}

	public void setStatus(int paramInt) {
		this.status = paramInt;
	}

	public int getSize() {
		return this.size;
	}

	public void setSize(int paramInt) {
		this.size = paramInt;
	}

	public String getMessage() {
		return this.message;
	}

	public void setMessage(String paramString) {
		this.message = paramString;
	}
}